var browser = require('browser-sync').create();
const net = require('net');

function checkPort(port, callback, host = '127.0.0.1') {
  const tester = net
    .createServer()
    .once('error', (err) => {
      if (err.code === 'EADDRINUSE') {
        callback(null, true); 
      } else {
        callback(err, null);
      }
    })
    .once('listening', () => {
      tester.once('close', () => {
        callback(null, false); 
      });
      tester.close();
    })
    .listen(port, host);
}

let isStartBrowser = false;
const browserInit = function (url) {
  checkPort(8080,function (err, inUse) {
    if (err) {
      console.error('检查端口时出错:', err);
    } else if (inUse) {
      console.log('端口 8080 被占用');
    } else {
      browser.init(
        {
          proxy: 'http://localhost:3030',
          files: ['src/*'],
          port: 8080,
        },
        function () {
          console.log('browser refreshed.');
        }
      );
      isStartBrowser = true;
    }
  });
};

exports.browserInit = function () {
  if (isStartBrowser) {
    browser.reload();
  } else {
    browserInit();
  }
};

exports.reload = function () {
  console.log('刷新浏览器');
  browser.reload();
};
